<template>
  <ElDialog :title="title" v-model="isOpen" width="40%" append-to-body @closed="handleBeforeClose">
    <avue-form :option="option" v-model="form" ref="listFormRef" @submit="handleSubmit">
      <template #menuIds>
        <avue-tree ref="treeRef" :option="treeOption" :data="treeData" />
      </template>
    </avue-form>
    <template #footer>
      <el-button type="primary" @click="listFormRef.submit()">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
import { ref, nextTick, onMounted } from "vue";
import { ElMessage } from "element-plus";
import type { IOpenFromDialog } from "@/views/commonType/paramsType";
import useFormOption from "../combination/useFormOption";
import useMenuTree from "../combination/useMenuTree";
import { addApi, updateApi, getDetailApi } from "@/api/system/role";
import { resetForm, treeSearch } from "@/utils/tool";

const emit = defineEmits(["done"]);
const defaultData = {
  roleSort: 1,
  status: "1",
  menuIds: [],
};

const { treeOption, treeData, initMenuTree } = useMenuTree();
const ntype = ref("");
const listFormRef = ref();
const option = useFormOption();
const form = ref<any>(defaultData);
const title = ref("新增");
const isOpen = ref(false);

const treeRef = ref();
async function handleSubmit(data: any, done: () => void) {
  data.menuIds = treeRef.value.getCheckedKeys();

  // const ids = treeRef.value.getCheckedKeys();
  // for (const id of ids) {
  //   const node = treeSearch(treeData.value, "id", id);
  //   if (node) {
  //     ids.push(node.parentId);
  //   }
  // }
  // const s = new Set(ids);
  // s.delete(0);
  // data.menuIds = [...s];
  try {
    if (ntype.value === "add") {
      await addApi(data);
    }
    if (ntype.value === "edit") {
      await updateApi(data);
    }
    ElMessage.success("操作成功");
    cancel();
    emit("done");
  } catch (err) {}
  done();
}

async function fetchData(id: string) {
  const res = await getDetailApi(id);
  form.value = res.data;

  treeRef.value.setCheckedKeys(res.data.menuIds);
}

async function init(params: IOpenFromDialog) {
  form.value = defaultData;
  isOpen.value = true;
  ntype.value = params.type;

  await nextTick();
  if (params.id) {
    fetchData(params.id);
  }
}

function cancel() {
  isOpen.value = false;
}

function handleBeforeClose() {
  resetForm(form, defaultData, listFormRef);
}

onMounted(() => {
  initMenuTree();
});

defineExpose({
  init,
});
</script>
